package com.bishe.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.StrUtil;
import com.api.Result;
import com.api.entitis.User;
import com.api.entitis.model.LoginModel;
import com.api.entitis.model.UserModel;
import com.api.entitis.query.UserQuery;
import com.api.service.IUserService;
import com.api.util.CompanyStpUtil;
import com.api.util.JobUtils;
import com.api.util.UserStpUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @date 2022/2/15 14:29
 */
@RestController
@CrossOrigin  //跨域处理
@RequestMapping("/user")
@Api(tags = "用户管理")
public class UserController {

    @Autowired
    private IUserService userService;

    @ApiOperation("登录")
    @PostMapping("/login")
    public Result login(@RequestBody LoginModel loginModel){
        //登录效验
        JobUtils.checkLoginModel(loginModel);

        UserModel login = userService.login(loginModel);
        if (login!=null){
            return Result.ok("ok",login);
        }
        return Result.error("用户名密码错误!");
    }



    @ApiOperation("注册和修改")
    @PostMapping("/registerOrUpdate")
    public Result registerOrUpdate(@RequestBody User user){
        if (user == null){
            return Result.error("user为空！");
        }

        if (StrUtil.isEmpty(user.getUserName())||
                StrUtil.isEmpty(user.getPassWord())||
                user.getAge()==null||
                StrUtil.isEmpty(user.getSex())||
                StrUtil.isEmpty(user.getEmail())
        )   {
            return Result.error("个人信息不能为空！");
        }

        //验证码校验
        JobUtils.checkImgCode(user.getTxt());
        userService.registerOrUpdate(user);

        return Result.ok();
    }

    @ApiOperation("是否登录")
    @GetMapping("/isLogin")
    @SaCheckLogin(type = UserStpUtil.TYPE)  //检查用户是否登录
    public Result isLogin(){

        return Result.ok();
    }

    @ApiOperation("用户列表")
    @GetMapping("/list")
    public Result toPage(UserQuery query){

        IPage<User> userIPage = userService.toPage(query);
        return Result.ok(userIPage);

    }

    @ApiOperation("退出登录")
    @PostMapping("/loginOut")
    public Result loginOut( ){
        StpUtil.logout();//admin退出登录
        CompanyStpUtil.logout(); //企业退出登录
        UserStpUtil.logout(); //用户退出登录

        return Result.ok();
    }

}
